package com.gmall.rabbitmq.producer.controller;

import com.gmall.rabbitmq.config.RabbitMQConfig_Reliable;
import com.gmall.rabbitmq.producer.utils.IdWorker;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/reliable")
public class ReliableController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    IdWorker idWorker;
    @GetMapping("sendMessage")
    public String sendMessage() {

        System.out.println("保存到Redis中----");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        /**
         * String exchange,
         * String routingKey,
         * Object message,
         * MessagePostProcessor messagePostProcessor,
         * @Nullable CorrelationData correlationData //confirm
         */
        Long messageId = idWorker.nextId();
        System.out.println("messageId = " + messageId);
        rabbitTemplate.convertAndSend(
                RabbitMQConfig_Reliable.Exchange_Direct_Reliable,
                RabbitMQConfig_Reliable.RoutingKey_Reliable,
                "Hello 2109A ==> " + simpleDateFormat.format(new Date()),
                message -> {
                    message.getMessageProperties().setMessageId(messageId.toString());
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);//消息也要持久化

                    return  message;
                },
                new CorrelationData(messageId.toString())
        );
        return "success";
    }
}
